package com.p7.framework.permission.web.ext.shiro;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author Yangzhen
 * @Description
 * @date 2019-10-23 15:27
 **/
@Aspect
@Component
public class OnlineAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(OnlineAspect.class);

    @Resource
    private OnlineService onlineService;

    @Pointcut()
    public void login() {
    }

    @Pointcut()
    public void logout() {
    }

    @Around(value = "login()")
    public Object afterLogin(ProceedingJoinPoint joinPoint) {
        try {
            Object result = joinPoint.proceed();
            if (result != null) {
                if (result instanceof Map) {
                    Map resultMap = (Map) result;
                    Object code = resultMap.get("code");
                    String codeStr = null;
                    if (code != null && StringUtils.isNumeric(codeStr = code.toString()) && Integer.valueOf(codeStr.toString()) == 0) {
                        Map data = (Map) resultMap.get("data");
                        Object waitActivate = data.get("waitActivate");
                        if (waitActivate != null) {
                            return result;
                        }
                        onlineService.doOnline();
                    }
                }
            }
            return result;
        } catch (Throwable throwable) {
            LOGGER.error("afterLogin error , {}", throwable.getMessage());
        }
        return "ERROR";
    }

    @Around(value = "logout()")
    public Object afterLogout(ProceedingJoinPoint joinPoint) {

        Object loginInfo = new Object();
        try {
            Object result = joinPoint.proceed();
            if (result != null) {
               if (result instanceof Map) {
                    Map resultMap = (Map) result;
                    Object code = resultMap.get("code");
                    String codeStr = null;
                    if (code != null && StringUtils.isNumeric(codeStr = code.toString()) && Integer.valueOf(codeStr.toString()) == 0) {
                        onlineService.doOffline(loginInfo);
                    }
                }
            }
            return result;

        } catch (Throwable throwable) {
            LOGGER.error("afterLogout error , {}", throwable.getMessage());
        }
        return "ERROR";
    }

}
